﻿
namespace EasyNet.Solr.Commons
{
    using System.IO;
    using System.Text;

    /// <summary>
    /// 文本格式数据编解码器
    /// </summary>
    public class TextCodec : ICodec
    {
        /// <summary>
        /// 字符编码
        /// </summary>
        public Encoding Encoding { get; set; }

        /// <summary>
        /// 默认构造函数
        /// </summary>
        public TextCodec()
        {
            Encoding = Encoding.UTF8;
        }

        /// <summary>
        /// 编码
        /// </summary>
        /// <param name="obj">编码对象</param>
        /// <param name="stream">输出流</param>
        public void Marshal(object obj, Stream stream)
        {
            byte[] bytes = Encoding.GetBytes(obj.ToString());

            stream.Write(bytes, 0, bytes.Length);
        }

        /// <summary>
        /// 解码
        /// </summary>
        /// <param name="stream">输入流</param>
        /// <returns>解码后的对象</returns>
        public object Unmarshal(Stream stream)
        {
            StreamReader sr = null;

            try
            {
                sr = new StreamReader(stream, Encoding);

                return sr.ReadToEnd();

            }
            finally
            {
                if (sr != null)
                {
                    sr.Close();
                }
            }
        }
    }
}
